package com.xxl.sso.core.login;

import java.util.UUID;

import com.xxl.sso.core.data.SsSsoCacheData;
import com.xxl.sso.core.store.SsoLoginStore;
import com.xxl.sso.core.user.XxlSsoUser;

/**
 * @author xuxueli 2018-11-15 15:54:40
 */
public class SsoTokenLoginHelper {

    /**
     * client login
     *
     * @param sessionId
     * @param xxlUser
     */
    public static String login(String userId, String username) {
        String accessToken = UUID.randomUUID().toString().replaceAll("-", "");

        XxlSsoUser xxlUser = new XxlSsoUser();
        xxlUser.setUserid(userId);
        xxlUser.setUsername(username);
        xxlUser.setAccessToken(accessToken);
        xxlUser.setExpireMinite(SsoLoginStore.getRedisExpireMinite());
        xxlUser.setExpireFreshTime(System.currentTimeMillis());

        SsSsoCacheData.accessTokenUserIdMap.put(accessToken, userId);

        SsoLoginStore.put(userId, xxlUser);

        return accessToken;
    }

    public static void updateAccessTokenUserIdMap(String accessToken, String userId) {
        SsSsoCacheData.accessTokenUserIdMap.put(accessToken, userId);
    }

    /**
     * client logout
     *
     * @param sessionId
     */
    public static void logout(String accessToken) {
        String userId = SsSsoCacheData.accessTokenUserIdMap.get(accessToken);

        SsoLoginStore.remove(userId);

        SsSsoCacheData.accessTokenUserIdMap.remove(accessToken);

        LogoutManager.logout(accessToken);
    }

    /**
     * login check
     *
     * @param sessionId
     * @return
     */
    public static XxlSsoUser loginCheckByAccessToken(String accessToken){
        String userId = SsSsoCacheData.accessTokenUserIdMap.get(accessToken);

        return loginCheckByUserId(userId);
    }

    public static XxlSsoUser loginCheckByUserId(String userId){
        XxlSsoUser xxlUser = SsoLoginStore.get(userId);
        if (xxlUser != null) {
            // After the expiration time has passed half, Auto refresh
            if ((System.currentTimeMillis() - xxlUser.getExpireFreshTime()) > xxlUser.getExpireMinite() / 2) {
                xxlUser.setExpireFreshTime(System.currentTimeMillis());
                SsoLoginStore.put(userId, xxlUser);
            }
            return xxlUser;
        }
        return null;
    }
}
